const app = getApp()
Page({
  data: {
    base_url: "https://deh.lzsjyfz.com/",
    userInfo: null,
    hasUserInfo: true,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    src:'',
    debug:false,
    shareData:{}
  },
  onLoad(option) {
    
    let that = this;
    console.log('reload')
    Promise.resolve().then(function(){
       //获取token;
       return that._login();
    }).then(function(res){
      console.log('login user', res)
      that.setData({
        debug:app.globalData.debug
      });
      //封装景区url
      return that._sceneurl(option);
    }).then(function(res){
      // 位置鉴权
      that.updateLocation();
    });
  },
  onShow(e){
    let that = this;
    // that.checkFunAuth();
    // that.updateLocation();
    wx.setNavigationBarTitle({
      title: '智慧导览',
    });
    wx.showTabBar({
      animation: true,
      complete:function(res){
        console.log('res', res)
      }
    })
  },
 //用户位置授权
  updateLocation:function(){
    let that = this;
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userLocation']) {
          wx.authorize({
            scope: 'scope.userLocation',
            success (e) {
              console.log(e);
              that.getLocation();
            },
            fail(e){
              console.log(e);
            }
          })
        }
        else{
          that.getLocation();
        }
      }
    })
  },//检测位置变化
  getLocation:function(){
    console.log('getlocation');
    let that = this;
    // wx.startLocationUpdateBackground({
    wx.startLocationUpdate({
      success:function(e){
        const _locationChangeFn = function(res) {
          // check openid then post 
          console.log(res);
          if(that.data.userInfo && that.data.userInfo.openid != ''){
            let lat = Number(wx.getStorageSync('lat'));
            let lng = Number(wx.getStorageSync('lng'));
            console.log(res);
            if(lat != Number(res.latitude) || lng != Number(res.longitude)){
              that.postLocation(res);
            }
          }
         }
         wx.onLocationChange(_locationChangeFn)
      },
      fail(e){
        console.log(e);
      },
      complete(e){
        console.log(e);
      }
    });
  },
  //登录获取token
  _login(){
    let that = this;
    return new Promise((resolve, reject)=>{
      if(wx.getStorageSync('accessToken') && wx.getStorageSync('user')) {
         let userInfo  = wx.getStorageSync('user');
         console.log('userinfo', userInfo)
         that.setData({
          userInfo:userInfo
        })
        resolve(userInfo)
      }
      else {
        wx.login({
          success:(res)=>{
            const data = {
              code:res.code,
              app_id:app.app_id
            }
            console.log(res.code)
            app.api.post(app.getUrl('login'), data).then((res)=>{
              console.log(res)
              wx.setStorageSync('accessToken', res.data.access_token)
              that.setData({
                userInfo:res.data.wechat_user
              })
              resolve(res)
            })
          }
        })
      }

      

    });
  },//获取景区链接
  _sceneurl(option){
    let that = this;
    return new Promise((resolve, reject)=>{
      console.log('userinfo', that.data.userInfo);
      let src = that.data.base_url+'mobile/dist/#/?openid='+that.data.userInfo.openid+'&timestamp='+Date.now();
      if(option.allspot) {
        src +='&allspot=1'
      }
      if(option.service) {
        src += '&service=1';
      }

      if(option.path) {
        src += '&pathid='+option.path
      }

      if(option.type == 'post') {
        let spotid = option.spotid;
        src += '&type=post&spotid='+spotid
      }

      that.setData({
        src: src,
        // shareData:res.data.data.shareData
      });
      resolve(1);
   });
  },//更新用户信息
  getUserInfo(e) {
    //更新用户信息
    let that = this;
    if(e.detail.errMsg !="getUserInfo:ok"){
        return false;
    }
    return new Promise((resolve,reject)=>{
        // 更新用户信息
       let url = that.data.base_url+'api/wechat/mini/decrypt-user-info';
       let token = wx.getStorageSync('accessToken');
       console.log(e.detail);
       let data = {
        app_id:app.globalData.appid,
        iv:e.detail.iv,
        encrypted_data:e.detail.encryptedData
       };
       wx.request({
         url: url,
         data:data,
         header:{
           'Authorization':token
         },
         method:'POST',
         success(res){
              if(!res.error_code){
                that.setData({
                  hasUserInfo:true
                })
              }
             resolve(res.data.data);
         }
       })
    });
  },//上传位置信息
  postLocation(data){
    let that = this;
    let url = that.data.base_url+'/api/v1/location/update';
    let latitude = data.latitude;
    let coordinate = {
      latitude:data.latitude,
      longitude:data.longitude
    };
    wx.setStorageSync('lat', data.latitude);
    wx.setStorageSync('lng', data.longitude);
    let token = wx.getStorageSync('accessToken');
    wx.request({
      url: url,
      method:'POST',
      data:{
        openid:that.data.userInfo.openid,
        coordinate:coordinate,
      },
      header:{
        'Authorization':token
      },
      success(res){
      }
    })
  },
  alert(param1, param2){
    // wx.showModal({
    //   title:param1,
    //   content:param2
    // })
  },//转发
  onShareAppMessage(){
    let that = this;
    // return {
    //   title: that.data.shareData.title? that.data.shareData.title:'道可云智能导览系统',
    //   desc: that.data.shareData.desc? that.data.shareData.desc:'',
    //   path: that.data.shareData.path? that.data.shareData.path:'/pages/index/index'
    // }
  },
  onShareTimeline(){
    // return {
    //   title: that.data.shareData.title? that.data.shareData.title:'道可云智能导览系统',
    //   imageUrl:that.data.shareData.img? that.data.shareData.img:''
    // }
  }
})
